package com.eshop.config;

import java.nio.charset.StandardCharsets;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;

class FastJsonRedisSerializer<T> implements RedisSerializer<T>
{
    private final Class<T> clazz;
    
    FastJsonRedisSerializer(final Class<T> clazz) {
        this.clazz = clazz;
    }
    
    public byte[] serialize(final T t) {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString((Object)t, new SerializerFeature[] { SerializerFeature.WriteClassName }).getBytes(StandardCharsets.UTF_8);
    }
    
    public T deserialize(final byte[] bytes) {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        final String str = new String(bytes, StandardCharsets.UTF_8);
        return (T)JSON.parseObject(str, (Class)this.clazz);
    }
}
